import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const path = require('path')
const { app, shell, BrowserWindow, protocol, ipcMain } = require('electron')
const { autoUpdater } = require('electron-updater')

process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'vite-electron', privileges: { secure: true, standard: true } }
])

// 主窗口
let mainWindow
function createWindow () {
  mainWindow = new BrowserWindow({
    width: 600,
    height: 600,
    nodeIntegration: true,
    contextIsolation: false,
    autoHideMenuBar: true,
    webPreferences: {
      sandbox: false,
      webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.on('close', function () {
    mainWindow = null
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (!app.isPackaged) {
    mainWindow.loadURL('http://localhost:8080/index.html#/')
  } else {
    createProtocol('app')
    mainWindow.loadURL('app://./index.html')
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  if (app.isPackaged) updateHandle()
})

// 退出应用时清除定时器
app.on('will-quit', () => {
  clearInterval()
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
// 在mac中，关闭窗口并不一定代表关闭应用程序。当最后一个窗口被关闭时，应用程序将保持运行状态。
// 如果需要在关闭最后一个窗口时关闭应用程序，请在window-all-closed事件中调用app.quit()方法。
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// dialog窗口
ipcMain.on('show', () => {
  let newWindow
  newWindow = new BrowserWindow({
    width: 400,
    height: 400,
    alwaysOnTop: true,
    nodeIntegration: true,
    contextIsolation: false,
    autoHideMenuBar: true,
    webPreferences: {
      sandbox: false,
      webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })
  if (!app.isPackaged) {
    newWindow.loadURL('http://localhost:8080/about.html#/')
  } else {
    createProtocol('app')
    newWindow.loadURL('app://./about.html')
  }
  newWindow.on('closed', () => {
    newWindow = null
  })
})

function updateHandle () {
  const message = {
    error: '检查更新出错',
    checking: '正在检查更新……',
    updateAva: '检测到新版本，正在下载……',
    updateNotAva: '已经是最新版本，不用更新'
  }
  const feedUrl = 'http://oss.poooli.com/download/app/desktop/' + process.platform
  // 设置上传的服务器地址
  autoUpdater.setFeedURL(feedUrl)
  autoUpdater.on('error', function (error) {
    sendUpdateMessage(message.error, error)
  })
  // 在检查更新是否开始时发出。
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage(message.checking, '')
  })
  /**
   * info UpdateInfo（适用于通用和github提供程序）| VersionInfo（用于Bintray提供程序）
   * 有可用更新时发出。如果autoDownload为，则会自动下载更新true。
   */
  autoUpdater.on('update-available', function (info) {
    sendUpdateMessage(message.updateAva, info)
  })
  // 没有可用更新时触发
  autoUpdater.on('update-not-available', function (info) {
    sendUpdateMessage(message.updateNotAva, info)
  })

  // 更新下载进度事件
  autoUpdater.on('download-progress', function (progressObj) {
    mainWindow.webContents.send('downloadProgress', progressObj)
  })
  // 开始下载
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    /**
     * 和渲染进程通信，如果接收到"isUpdateNow"则调用autoUpdater.quitAndInstall();
     * 退出应用程序并安装
     */
    ipcMain.on('isUpdateNow', (e, arg) => {
      console.log(arguments)
      console.log('开始更新')
      // some code here to handle event
      autoUpdater.quitAndInstall()
    })

    mainWindow.webContents.send('isUpdateNow')
  })

  ipcMain.on('checkForUpdate', () => {
    // 执行自动更新检查
    autoUpdater.checkForUpdates()
  })
}

// 通过main进程发送事件给renderer进程，提示更新信息
function sendUpdateMessage (text, info) {
  mainWindow.webContents.send('message', text, info)
}
